<!--
 * @Description    : 云片人机验证
 * @Version        : 1.0.0
 * @Author         : QianLong
 * @Date           : 2021-04-22 20:28:21
 * @LastEditors    : QianLong
 * @LastEditTime   : 2021-05-11 10:55:36
-->
<template>
  <div class="Yp">
    <div :id="id" class="middleCenter wrap"></div>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { requestFailed } from '@/utils/feedback'

export default defineComponent({
  name: 'YunPian',
  props: {
    id: {
      type: String,
      default: 'wrap'
    },
    appId: {
      type: String,
      default: ''
    }
  },
  emits: ['onSuccess', 'onFail', 'onError'],
  setup(props, { emit }) {
    function getYunPian() {
      /* eslint-disable no-new */
      new (window as any).YpRiddler({
        expired: 30,
        mode: 'dialog',
        winWidth: 400,
        lang: 'zh-cn',
        container: document.getElementById(props.id),
        appId: props.appId,
        version: 'v1',
        onError: function (param) {
          emit('onError', param)
          if (!param.code) {
            requestFailed(null, '错误请求')
          } else if (param.code == 500) {
            // 服务不可用时，开发者可采取替代方案
            requestFailed(null, '验证服务暂不可用')
          } else if (param.code == 429) {
            requestFailed(null, '请求过于频繁，请稍后再试')
          } else if (param.code == 403) {
            requestFailed(null, '请求受限，请稍后再试')
          } else if (param.code == 400) {
            requestFailed(null, '非法请求，请检查参数')
          }
          requestFailed(null, '验证服务异常')
        },
        onSuccess: function (validInfo, close, useDefaultSuccess) {
          // 成功回调
          // alert('验证通过! token=' + validInfo.token + ', authenticate=' + validInfo.authenticate)
          // 验证成功默认样式
          useDefaultSuccess(true)
          close()
          emit('onSuccess', validInfo)
        },
        onFail: function (code, msg, retry) {
          // 失败回调
          // alert('出错啦：' + msg + ' code: ' + code)
          retry()
          emit('onFail', code, msg)
        },
        beforeStart: function (next) {
          next()
        }
      })
    }
    return {
      getYunPian
    }
  }
})
</script>

<style scoped>
.wrap {
  width: 100%;
  height: 40px;
}
</style>
